﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AStar.Collections;
using AStar.Class;

namespace AStar.Logic
{
    class Logic
    {
        MyHash<String, MyList<City>> streets;
        OpenList<City> openList = new OpenList<City>();
        MyHash<String, City> closedList = new MyHash<string, City>();

        public Logic()
        {
            streets = new MyHash<string, MyList<City>>();
        }

        public void addOneWay(City from, City to, float length)
        {
            if (!streets.exists(from.Name))
            {
                streets[from.Name] = new MyList<City>();
            }
            City temp = new City(to.Name, to.X, to.Y);
            temp.Lenght = length;
            streets[from.Name].add(temp);
        }

        public void addStreet(City from, City to, float length)
        {
            addOneWay(from, to, length);
            addOneWay(to, from, length);
        }

        public MyList<City> getShortestRoute(City from, City to)
        {
            MyList<City> re = new MyList<City>();

            addNeighbours(from,to);

            return re;
        }

        private void addNeighbours(City from,City to)
        {
            City now;
            for (int i = 0; i < streets[from.Name].Count(); i++)
            {
                now = streets[from.Name].get(i);
                if (!from.Before.Name.Equals(now.Name))
                {
                    City temp = new City(to.Name, to.X, to.Y);
                    temp.Lenght = now.Lenght + from.Lenght;
                    now = temp;
                    now.Before = from;
                    now.estimate(to);
                    openList.add(now);

                }
            }
            openList.Remove(from);
            if (closedList.exists(from.Name))
            {
                if (closedList[from.Name].MaxLength > from.MaxLength)
                {
                    closedList[from.Name] = from;
                }
            }
            else
            {
                closedList[from.Name] = from;
            }
        }
    }
}
